import pyautogui
import cv2
import numpy as np
from time import sleep
from pynput.mouse import Button, Controller

#! 加载模板 1
template_image = cv2.imread('Python\\python_project\\eyes_3rd\\screenshotLib\\target1.png',0)
# 获取模板图像的宽度和高度
h,w = template_image.shape
#加载鼠标控制
mouse = Controller()
#精准度
threshold = 0.8


while True:
    screenshot = pyautogui.screenshot()         #! PTI图像 
    #! 将PIL图像转换为OpenCV可用的NumPy数组（BGR格式）
    screenshot_np = np.array(screenshot)
    screenshot_cv = cv2.cvtColor(screenshot_np,cv2.COLOR_RGB2BGR)

    gray_screenshot = cv2.cvtColor(screenshot_cv,cv2.COLOR_BGR2GRAY)    #! 将需要识别的图片转换为灰度
    result = cv2.matchTemplate(gray_screenshot,template_image,cv2.TM_CCOEFF_NORMED)

    tagets = np.where(result >= threshold)

    if len(tagets[0]) > 0:
        print(f"找到了{len(tagets[0])}个匹配")
        for pt in zip(*tagets[::-1]):
            center_x = pt[0] + w // 2
            center_y = pt[1] + h // 2
            center_point = (center_x, center_y)
            print(f"匹配区域中心点坐标: {center_point}")
            mouse.position = center_point # 移动鼠标到匹配区域中心
            # 根据需要执行点击等其他操作
            sleep(3)


    # min_val,max_val,min_loc,max_loc = cv2.minMaxLoc(result)
    # if max_val >= threshold:
    #     mouse_x,mouse_y = pyautogui.position()
    #     print(f"当前鼠标坐标{mouse_x,mouse_y}")

    #     # print("找到")
    #     top_left = max_loc  # 匹配到的区域左上角坐标  更名!
    #     #* 计算中心点坐标   高的一半和宽的一半
    #     center_x = top_left[0] + w // 2
    #     center_y = top_left[1] + h // 2
    #     center_point = (center_x, center_y)
    #     # 输出中心点坐标
    #     print(f"匹配区域中心点坐标: {center_point}")
    #     # 移动鼠标
    #     # mouse.position = (center_point)

    # else:
    #     print("没找到")
    # sleep(3)